package com.ewei.web.authority.shiro.stateless;

import java.net.URLDecoder;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Value;

import com.ewei.web.authority.utils.TokenUtils;
import com.ewei.web.common.http.HttpUtils;
import com.ewei.web.common.json.JsonUtils;
import com.ewei.web.common.response.ResponseVO;
import com.ewei.web.common.utils.Encrypter;
public class StatelessAuthFilter extends AccessControlFilter{
	private String loginUrl = "/loginPage";
	@Resource
	private TokenUtils tokenUtil;
	@Resource
	private Encrypter encrypter;
	//@Value("${session.timeout.minute}")
	private Integer sessionTimeOut;
	private final String unAuthMessage = "{\"status\":\"666666\",\"datas\":\"%s\"}";//默认信息
	@Override
	protected boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {
		return false;
	}

	@SuppressWarnings("static-access")
	@Override
	protected boolean onAccessDenied(ServletRequest request,
			ServletResponse response) throws Exception {
		HttpServletRequest req = WebUtils.toHttp(request);;
		Cookie[] cookies = req.getCookies();
		String cookieValue = null;
		if(null!=cookies&&cookies.length>0){
			for(Cookie cookie:cookies){
				String cookieName = cookie.getName();
				if(cookieName.equals(tokenUtil.COOKIE_NAME)){
					cookieValue =URLDecoder.decode(cookie.getValue(),"UTF-8");
				}
			}
		}
		if(null == cookieValue){
			forward(request,response,"没有登陆");
			return false;//没有登录 
		}
		String[] tokenAndAuth = cookieValue.split(",");
		String tokenValue = tokenAndAuth[0];
		String authDecode = encrypter.base64Decoder(tokenAndAuth[1]);
		String timeStamp = tokenUtil.getTimeFromAuth(authDecode);
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		ParsePosition position = new ParsePosition(0);
		Date lastAccessTime = format.parse(timeStamp, position);
		System.out.println(authDecode);
		System.out.println(timeStamp);
		System.out.println(lastAccessTime);
		if(System.currentTimeMillis()-lastAccessTime.getTime()>sessionTimeOut*60000){
			forward(request,response,"登陆超时");
			return false;//登录超时
		}
		String username = tokenUtil.getUserNameFromAuth(authDecode);
		StatelessToken token = new StatelessToken(username,tokenValue,tokenAndAuth[1]);
		Subject subject = SecurityUtils.getSubject();
		try{
			subject.login(token); //无状态登录
		}catch(Exception e){
			e.printStackTrace();
			if(e instanceof IncorrectCredentialsException){ //错误的登录凭证
				forward(request,response,"错误的凭证");
			}
			return false;
		}
		return true;
	}
	private void forward(ServletRequest request,ServletResponse response,String message){
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httpResponse = (HttpServletResponse)response;
		try{
			if(HttpUtils.isAjax(httpRequest)){
				String json = String.format(unAuthMessage, message);
				json = JsonUtils.toJson(JsonUtils.fromJson(json, ResponseVO.class),null);
				httpResponse.setContentType("application/json;charset=UTF-8");
				httpResponse.getWriter().write(json);
			}else{
				httpResponse.sendRedirect(httpRequest.getContextPath()+loginUrl);
			}
		}catch(Exception e){
			throw new RuntimeException(e);
		}
	}
}
